<?php
class serviceController extends commonController {

    /*
     * 抓未推送的指派订单
     */
    public function pushExpressOrdersAction() {
        $express_order = $this->model->GetExpressOrders();
        $order=array();
        $log = new Logging();
        $log->lfile('push_express_order');
        $log->lwrite('express_order:'.is_array($express_order)?count($express_order):0);
        if (!empty($express_order)){
            foreach($express_order as $key=>$val){
                $order[$key] = $this->model->getItemById($val['orders_id'],'orders');
                $where = array('AND'=>array('='=>array('orders_id'=>$val['orders_id'],'createid' => $val['shop_no'], 'isdeleted' => 0, 'status' => 1)));
                $shop_delivery_address = $this->model->getItemByOther($where,'shop_delivery_address');

                    if($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0){
                        rsort($shop_delivery_address);
                        # 拿到最新门店修改地址
                    $order[$key]['receiver'] = $shop_delivery_address[0]['receiver_name'];
                    $order[$key]['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
                    $order[$key]['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
                    $order[$key]['slat'] = $shop_delivery_address[0]['lat']; # 20200426 纬度
                    $order[$key]['slng'] = $shop_delivery_address[0]['lng']; # 20200426 经度
                }

                $order[$key]['express_type'] = $val['express_type'];
                $order[$key]['jrd_type'] = $val['jrd_type'];
                $order[$key]['actual_weight'] = $val['shop_goods_weight'];
                $order[$key]['shop_express_no'] = $val['shop_express_no']; # 指派 门店编号+运单编号+指派ID
                $order[$key]['shop_pickup_time'] = $val['shop_pickup_time']; # 指派 门店设定取货时间
                $order[$key]['shop_delivery_time'] = $val['shop_delivery_time']; # 指派 门店设定预计到达时间
                $order[$key]['shop_express_remark'] = $val['shop_express_remark']; # 指派 门店指派备注
                $order[$key]['sf_push_type'] = $val['sf_push_type']; # 指派 湖南分司门店指派顺丰推送商品类型
                $order[$key]['is_direct_delivery'] = $val['is_direct_delivery']; # 指派 达达专属配送类型

                if (!empty($order)){
                    $where = array("AND" => array("=" => array("ph_no" => $val['ph_no'],"status" => 1,"isdeleted" => 0)));
                    $orderby=array('id'=>'asc');
                    $orders_product=$this->model->getAll($where, 'orders_product', $orderby);
                    $order[$key]['products']=$orders_product;
                }
            }

            if (!empty($order)) {
                # 获取门店信息
                foreach ($order as &$oval) {
                    $where_fields = array("AND" => array("=" => array('store_id' => $oval['shop_no'])));
                    $store = $this->model->getItemByOther($where_fields, 'xd_store');
                    $where_fields_company = array("AND" => array("=" => array('code' => $store[0]['company_id'])));
                    $company = $this->model->getItemByOther($where_fields_company, 'xd_company');

                    $oval['deliver_province'] = $store[0]['front_province'];
                    $oval['company_id'] = $store[0]['company_id']; # 门店所属分司代码
                    $oval['deliver_city'] = $store[0]['front_city'];
                    $oval['deliver_area'] = $store[0]['front_area'];
                    $oval['deliver_address'] = $store[0]['front_address'];
                    $oval['deliver_tel'] = $store[0]['tel'];   # 门店电话
                    $oval['deliver_lat'] = $store[0]['latitude'];
                    $oval['deliver_lng'] = $store[0]['longitude'];
                    $oval['deliver_phone'] = $store[0]['phone'];   # 门店手机号
                    $oval['deliver_store_id'] = $store[0]['store_id']; # 宅配门店id
                    $oval['deliver_express_id'] = $store[0]['express_id']; # 闪送用 平台门店id
                    $oval['jrd_sign'] = $store[0]['jrd_sign']; # 今日达 签名

                    # 20200415 修改闪送 达达开发资料在对应店铺下
                    $oval['ss_clientId'] = $store[0]['ss_clientId'];
                    $oval['ss_clientSecret'] = $store[0]['ss_clientSecret'];
                    $oval['ss_shopId'] = $store[0]['ss_shopId'];
                    $oval['dd_source_id'] = $store[0]['dd_source_id'];
                    $oval['dd_app_secret'] = $store[0]['dd_app_secret'];
                    $oval['dd_app_key'] = $store[0]['dd_app_key'];

                    # 20201109 新增UU跑腿
                    $oval['uu_app_id'] = $store[0]['uu_app_id'];
                    $oval['uu_app_key'] = $store[0]['uu_app_key'];
                    $oval['uu_open_id'] = $store[0]['uu_open_id'];

                    # 20201126 新增365
                    $oval['user365Id'] = $store[0]['user365Id'];
                    $oval['365pwd'] = $store[0]['365pwd'];
                    $oval['365serviceKey'] = $store[0]['365serviceKey'];

                    $oval['shop_longitude'] = $store[0]['longitude'];
                    $oval['shop_latitude'] = $store[0]['latitude'];


                    $city = explode('市', $store[0]['front_city']);
                    $oval['city'] = $city[0];
                    $oval['company'] = $company[0];
                }

                # 获取城市代码
                $where_fields_city = array("AND" => array("=" => array('status' => 1, 'isdeleted' => 0)));
                $field_city = 'city_code,city_name';
                $cityCodeList = $this->model->getAll($where_fields_city, 'city_code', '', $field_city);
                if($cityCodeList && count($cityCodeList) > 0){
                    foreach ($order as &$ovalu) {
                        foreach ($cityCodeList as $ctval) {
                            if ($ovalu['city'] == $ctval['city_name']) {
                                $ovalu['cityCode'] = $ctval['city_code'];
                            }
                        }
                    }
                }

                $config = Config::getInstance();
                $website_array = $config->getWebSiteConfig();
                $callbackUrl = $website_array['website_url'];
                foreach ($order as &$callback) {
                    $callback['callbackUrl'] = $callbackUrl;
                }

                $this->model->send_order($order);
            }else {
                $log->lwrite('无订单可推送.................');
                echo '<div style="position:fixed; left:50%;top:50%;font-size: 20px ">无订单可推送</div>';
            }
            $log->lwrite('完成.................');
            echo '<div style="position:fixed; left:50%;top:50%;font-size: 20px ">订单推送成功</div>';
        }else {
            $log->lwrite('无订单可推送.................');
            echo '<div style="position:fixed; left:50%;top:50%;font-size: 20px ">无订单可推送</div>';
        }

    }


    /**
     * 顺丰取消原因   顺丰主动回调
     * http://zhaipei.shjieta.com.cn/?md=service&cl=service&at=sfcancel
     *  返回一维数组
     */
    public function sfcancelAction(){
        $body = file_get_contents('php://input');
        $log=new Logging();
        $log->lfile('sf_callback');
        $log->lwrite('cancel body=>'.$body);
        //$body='{"shop_id":3243279847393,"sf_order_id":"3271731901788022785","shop_order_id":"100731_PH19053100002207_2","url_index":"sf_cancel","operator_name":"wl","operator_phone":"","order_status":2,"status_desc":"顺丰取消订单","push_time":1560083363,"cancel_reason":"","rider_lng":"","rider_lat":""}';
        $returnCancelInfo = json_decode($body,true);
        $log->lwrite('cancel receive=>'.json_encode($returnCancelInfo,JSON_UNESCAPED_UNICODE));

        if (!empty($returnCancelInfo)){
            $_result=array();
            $_result['shop_express_no'] = $returnCancelInfo['shop_order_id'];
            $_result['express_no'] = $returnCancelInfo['sf_order_id'];
            $_result['express_type'] = 'sf';
            $_result['express_code'] = $returnCancelInfo['order_status'];
            $_result['express_data'] = json_encode($returnCancelInfo,JSON_UNESCAPED_UNICODE);
            $_result['express_code_desc'] =$returnCancelInfo['status_desc'];
            $_result['express_result']="OK";
            $_result['shop_code'] = 8;
            $_result['shop_code_desc'] = Data::$_express_status[8].','.$returnCancelInfo['cancel_reason'];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5001;
            $log->lwrite('cancel add express_data=>'.json_encode($_result,JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');


            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields,'orders_express');

            //更新订单状态
            $field = array();
            $field['status'] = 0;
            $field['express_type'] = '';
            $field['updatedt'] = 'now()';
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');

            //更新指派订单状态
            $field = array();
            $field['status'] = 8;
            $field['updatedt'] = 'now()';
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');

            if($r_e_d && $r_o && $r_e){
                $return = ["error_code"=>0,"error_msg"=>"success"];
                $log->lwrite('cancel response=>'.$returnCancelInfo['shop_order_id'].','.json_encode($return,JSON_UNESCAPED_UNICODE));
                echo  json_encode($return, JSON_UNESCAPED_UNICODE);
                exit;
            }

        }
    }



    /**
     *  顺丰 订单状态回调
     * 10-配送员确认;12:配送员到店;15:配送员配送中
     * http://zhaipei.shjieta.com.cn/?md=service&cl=service&at=getcallbackstatus
     */
    public function getcallbackstatusAction(){
        $body = file_get_contents('php://input');
        $log=new Logging();
        $log->lfile('sf_callback');
        $log->lwrite('status body=>'.$body);
        $returnInfo = json_decode($body,true);
        $log->lwrite('status receive=>'.json_encode($returnInfo,JSON_UNESCAPED_UNICODE));
        if($returnInfo['order_status'] == 10 || $returnInfo['order_status'] == 12 || $returnInfo['order_status'] == 15){

            $shop_status=4;
            if($returnInfo['order_status'] == 10 || $returnInfo['order_status'] == 12){         # 宅配状态 = 3       顺丰 = 10 = 配送员接单 = 12 = 配送员到店
                $shop_status = 3;
            }else{                                                                              # 宅配状态 = 4       顺丰 = 15 配送员配送中
                $shop_status = 4;
            }

            # 某个状态下 顺丰小费追加 【重新整理】
//            $sfe = new SFExpressClass($website_array['debug'],$v['company']['sf_dev_key'],$v['company']['sf_dev_id'],$v['company']['sf_user_name']);
//            $addFee = $sfe->AddOrderGratuityFee($v['shop_express_no'],$v['shop_no'],$v['tip']);
//            $where = array('AND'=>array('='=>array('shop_no'=>$v['shop_no'],'order_no' => $v['shop_express_no'], "isdeleted" => 0, "status" => 1)));
//            $tip_res = $this->getItemByOther($where,'tip_list');
//            if($addFee && $addFee['error_code'] == 0){
//                $tip['push_state'] = 1;
//            }else{
//                $tip['push_state'] = 9;
//            }
//
//            if($tip_res && count((array)$tip_res) > 0){
//                $tip['push_time'] = 'now()';
//                $tip['ret_data'] = json_encode($addFee,JSON_UNESCAPED_UNICODE);
//                $where_fields = array("AND" => array("=" => array('id' => $tip_res[0]['id'], "isdeleted" => 0)));
//                $this->updateItem($tip, $where_fields, 'tip_list');
//            }


            $_result=array();
            $_result['shop_express_no'] = $returnInfo['shop_order_id'];
            $_result['express_no'] = $returnInfo['sf_order_id'];
            $_result['express_type'] = 'sf';
            $_result['express_code'] = $returnInfo['order_status'];
            $_result['express_code_desc'] =$returnInfo['status_desc'];
            $_result['express_data'] = json_encode($returnInfo,JSON_UNESCAPED_UNICODE);
            $_result['express_result']="OK";
            $_result['shop_code'] = $shop_status;
            $_result['shop_code_desc'] = Data::$_express_status[$shop_status];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5001;
            $log->lwrite('status add express_data=>'.json_encode($_result,JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');

            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields,'orders_express');

            $field = array();
            $field['status'] = $shop_status;
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5001;
            $where_fields = array("AND" => array("=" => array('id' =>  $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');

            $field = array();
            $field['status'] = $shop_status;
            $field['express_courier'] =$returnInfo['operator_name'];
            $field['express_mobile'] = $returnInfo['operator_phone'];
            $field['express_longtitude'] =$returnInfo['rider_lng'];
            $field['express_latitude'] = $returnInfo['rider_lat'];
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5001;
            $where_fields = array("AND" => array("=" => array('id' =>  $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');
            if($shop_status == 4){
                $data['shop_no'] = $order_express[0]['shop_no'];
                $data['orders_id'] = $order_express[0]['orders_id'];
                $data['notice_consignee'] = $order_express[0]['notice_consignee'];
                $data['rider_name'] = $order_express[0]['express_courier'];
                $data['rider_tel'] = $order_express[0]['express_mobile'];
                $this->OrgData($data);
            }

            if($r_e_d && $r_o && $r_e){
                $return = ["error_code"=>0,"error_msg"=>"success"];
                $log->lwrite('status response=>'.$returnInfo['shop_order_id'].','.json_encode($returnInfo,JSON_UNESCAPED_UNICODE));
                echo  json_encode($return, JSON_UNESCAPED_UNICODE);
                exit;
            }

        }
    }


    /**
     * 顺丰 订单完成回调
     * 17 配送员点击完成
     * http://zhaipei.shjieta.com.cn/?md=service&cl=service&at=getcallbackfinish
     */
    public function getcallbackfinishAction(){
        $body = file_get_contents('php://input');
        $log=new Logging();
        $log->lfile('sf_callback');
        $log->lwrite('finish body=>'.$body);
        $returnInfo = json_decode($body,true);
        $log->lwrite('finish receive=>'.json_encode($returnInfo,JSON_UNESCAPED_UNICODE));

        if (!empty($returnInfo)){
            $_result=array();
            $_result['shop_express_no'] = $returnInfo['shop_order_id'];
            $_result['express_no'] = $returnInfo['sf_order_id'];
            $_result['express_type'] = 'sf';
            $_result['express_code'] = $returnInfo['order_status'];
            $_result['express_data'] = json_encode($returnInfo,JSON_UNESCAPED_UNICODE);
            $_result['express_code_desc'] =$returnInfo['status_desc'];
            $_result['express_result']="OK";
            $_result['shop_code'] = 5;
            $_result['shop_code_desc'] = Data::$_express_status[5];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5001;
            $log->lwrite('finish add express_data=>'.json_encode($_result,JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');


            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields,'orders_express');

            //更新订单状态
            $field = array();
            $field['status'] = 5;
            $field['updatedt'] = 'now()';
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');

            //更新指派订单状态
            $field = array();
            $field['status'] = 5;
            $field['updatedt'] = 'now()';
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');
//            $data['shop_no'] = $order_express[0]['shop_no'];
//            $data['orders_id'] = $order_express[0]['orders_id'];
//            $data['notice_consignee'] = $order_express[0]['notice_consignee'];
//            $data['rider_name'] = $order_express[0]['express_courier'];
//            $data['rider_tel'] = $order_express[0]['express_mobile'];
//            $this->OrgData($data);

            if($r_e_d && $r_o && $r_e){
                $return = ["error_code"=>0,"error_msg"=>"success"];
                $log->lwrite('finish response=>'.$returnInfo['shop_order_id'].','.json_encode($return,JSON_UNESCAPED_UNICODE));
                echo  json_encode($return, JSON_UNESCAPED_UNICODE);
                exit;
            }
        }
    }



    /**
     * 闪送 回调订单状态
     * 订单状态,20:已支付，系统派单中，待抢单；30:骑手已抢单，取货中；40:骑手已取货，闪送中；50:闪送完成；60:已取消
     * http://zhaipei.shjieta.com.cn/?md=service&cl=service&at=GetSSCallBack
     * {"clientId":"ssGdrMKqvoXGVepo5","courier":{"blacklisted":0,"mobile":"","type":1},"deliveryPassword":"","issOrderNo":"19061118335121651","orderNo":"100614_PH19060400001297_136","pickupPassword":"174633","shopId":"18102411592549531","status":60,"statusDesc":"已取消","token":"615655100FC4B5DAAF06D46AC9292FBF"}
     */
    public function GetSSCallBackAction(){
        $body = file_get_contents('php://input');
        file_put_contents('logs/GetSSCall',$body,FILE_APPEND);
        $log=new Logging();
        $log->lfile('ss_callback');
        $log->lwrite('finish body=>'.$body);
        $returnInfo = json_decode($body,true);
        $log->lwrite('finish receive=>'.json_encode($returnInfo,JSON_UNESCAPED_UNICODE));
        $_result=array();
        if (!empty($returnInfo) && $returnInfo['status'] == 30 || $returnInfo['status'] == 40 || $returnInfo['status'] == 50 || $returnInfo['status'] == 60){
            if( $returnInfo['status'] == 30){ # 宅配=3待取件   30=3待取件 40=4配送中 50=5配送完成   60=6异常=闪送取消
                $shop_status = 3;
                $_result['express_result']="OK";
            }elseif ($returnInfo['status'] == 40){
                $shop_status = 4;
                $_result['express_result']="OK";
            }elseif($returnInfo['status'] == 50){
                $shop_status = 5;
                $_result['express_result']="OK";
            }else{
                $shop_status = 8;
                $_result['express_result']="fail";
            }
            $_result['shop_express_no'] = $returnInfo['orderNo'];
            $_result['express_no'] = $returnInfo['issOrderNo'];
            $_result['express_type'] = 'ss';
            $_result['express_code'] = $returnInfo['status'];
            $_result['express_code_desc'] =$returnInfo['statusDesc'];
            $_result['express_data'] = json_encode($returnInfo,JSON_UNESCAPED_UNICODE);
            $_result['shop_code'] = $shop_status;
            $_result['shop_code_desc'] = Data::$_express_status[$shop_status];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5004;
            $log->lwrite('status add express_data=>'.json_encode($_result,JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');

            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields,'orders_express');
            $field = array();
            if($shop_status == 8){
                $field['status'] = 0;
                $field['express_type'] = '';
            }else{
                $field['status'] = $shop_status;
            }
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5004;

            $where_fields = array("AND" => array("=" => array('id' =>  $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');

            $field = array();
            $field['status'] = $shop_status;
            $field['express_courier'] =$returnInfo['courier']['name'];
            $field['express_mobile'] = $returnInfo['courier']['mobile'];
            $field['express_longtitude'] =$returnInfo['courier']['longitude'];
            $field['express_latitude'] = $returnInfo['courier']['latitude'];
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5004;
            $where_fields = array("AND" => array("=" => array('id' =>  $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');

//            || $shop_status == 5
            if($shop_status == 4){
                $data['shop_no'] = $order_express[0]['shop_no'];
                $data['orders_id'] = $order_express[0]['orders_id'];
                $data['notice_consignee'] = $order_express[0]['notice_consignee'];
                $data['rider_name'] = $returnInfo['courier']['name'];
                $data['rider_tel'] = $returnInfo['courier']['mobile'];
                $this->OrgData($data);
            }
            if($r_e_d && $r_o && $r_e){
                $return = ["status"=>200,"msg"=>"订单状态同步成功"];
                $log->lwrite('finish response=>'.$returnInfo['orderNo'].','.json_encode($return,JSON_UNESCAPED_UNICODE));
                echo  json_encode($return, JSON_UNESCAPED_UNICODE);
                exit;
            }

        }

    }

    /**
     * 仅手动测试用
     * 闪送添加门店
     */
    public function SSAddStoreAction(){
        $sse = new SSExpressClass(TRUE,'ssGdrMKqvoXGVepo5','Xwt6FrQjQrBdmAvDKLzdWfuA17FRvmwQ','18102411592549531');
        $info_jj = $sse->add_shop();
        echo '<pre>';
        var_dump($info_jj);
    }


    /**
     * 仅手动测试用
     * 获取门店
     */
    public function SSGetStoresAction(){
        $sse = new SSExpressClass(TRUE,'ssGdrMKqvoXGVepo5','Xwt6FrQjQrBdmAvDKLzdWfuA17FRvmwQ','18102411592549531');
        $info_jj = $sse->get_shop_list();
        echo '<pre>';
        var_dump($info_jj);
    }



    /**
     * 仅手动测试用
     * 人人 模拟测试任意一个订单回调
     */
    public function testCallbackAction()

    {
        $rre = new RRExpressClass(TRUE,17321295203,'c693dd1c4594de59311ab4e2d1d0d381');
        $timeStamp = date('Y-m-d');
        $businessNo = '100046_PH19102100001058_50';
        $orderNo = '';
        $orderStatus = 9;                          # 需要获取的订单状态,值为【1-已接单,2-已取消,6-已签收,7-已取货，9-超时自动取消】,不传即为订单真实状态下的回调
        $operationType = '';                        # 配合orderStatus为2时生效，可用于更多的模拟状态：1-人人快递协助接单，2-人人快递协助取件，3-人人快递协助签收，5-人人快递取消接单
        $res = $rre->testCallback($timeStamp, $businessNo, $orderStatus, $operationType, 10);
        echo '配送信息：';
        var_dump($res);
        # 查询订单配送人信息
        $resInfo = $rre->query($timeStamp, $businessNo, 10);
        echo '<pre>';
        echo '查询订单:';
        var_dump($resInfo);

        $res1 = $rre->getorderdeliverer($timeStamp, $businessNo,10);
        echo '订单配送人信息:';
        var_dump($res1);

        $res2 = $rre->trail($timeStamp,$businessNo,10);
        echo '查询订单轨迹:';
        var_dump($res2);die;

    }

    /**
     * 人人  正式回调
     * 	公共参数，
     *  1 ：接单，                  2 ： 取件，
     *  3 ：签收，                  4 ：超时：一段时间内无人接单，系统自动取消订单，
     *  5：客服取消订单，           6：客服取消接单，
     *  7：客服协助接单，           8：客服协助取件，
     *  9：客服协助签收
     * http://zhaipei.shjieta.com.cn/?md=service&cl=service&at=GetRRCallBack
     */
    public function GetRRCallBackAction()
    {
        $body = file_get_contents('php://input');
        $log = new Logging();
        $log->lfile('rr_callback');
        $log->lwrite('finish body=>' . $body);
        $returnInfo = json_decode($body, true);
        $log->lwrite('finish receive=>' . json_encode($returnInfo, JSON_UNESCAPED_UNICODE));

        file_put_contents('logs/rrback_file',$body);

        if (!empty($returnInfo) && $returnInfo['msgType'] == 1 || $returnInfo['msgType'] == 2 || $returnInfo['msgType'] == 3 || $returnInfo['msgType'] == 4 || $returnInfo['msgType'] == 5|| $returnInfo['msgType'] == 6 || $returnInfo['msgType'] == 7 || $returnInfo['msgType'] == 8 || $returnInfo['msgType'] == 9) {
            if ($returnInfo['msgType'] == 1) {
                $shop_status = 3;
                $express_code_desc = '待取件';
            } elseif ($returnInfo['msgType'] == 3 || $returnInfo['msgType'] == 9) {
                $shop_status = 5;
                $express_code_desc = '完成配送';
            } elseif ($returnInfo['msgType'] == 4 || $returnInfo['msgType'] == 5 || $returnInfo['msgType'] == 6) {
                $shop_status = 8;
            } elseif($returnInfo['msgType'] == 2 || $returnInfo['msgType'] == 7 || $returnInfo['msgType'] == 8){
                $express_code_desc = '超时 系统自动取消订单';
                $shop_status =4;
                $express_code_desc = '配送中';
            }else{
                $shop_status = 5;
                $express_code_desc = '完成配送';
            }

            $_result = array();
            $_result['shop_express_no'] = $returnInfo['businessNo'];
            $_result['express_no'] = $returnInfo['orderNo'];
            $_result['express_type'] = 'rr';
            $_result['express_code'] = $returnInfo['msgType'];
            $_result['express_code_desc'] = $express_code_desc;
            $_result['express_data'] = json_encode($returnInfo, JSON_UNESCAPED_UNICODE);
            $_result['express_result'] = "OK";
            $_result['shop_code'] = $shop_status;
            $_result['shop_code_desc'] = Data::$_express_status[$shop_status];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5003;
            $log->lwrite('status add express_data=>' . json_encode($_result, JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');

            $where_fields = array("AND" => array("=" => array('shop_express_no' => $returnInfo['businessNo'])));
            $order_express = $this->model->getItemByOther($where_fields, 'orders_express');

            $field = array();
            if($shop_status == 8){
                $field['status'] = 0;
                $field['express_type'] = '';
            }else{
                $field['status'] = $shop_status;
            }
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5003;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');

            $field = array();
            $field['status'] = $shop_status;
            $field['express_courier'] = $returnInfo['deliverer_name'];
            $field['express_mobile'] = $returnInfo['deliverer_phone'];
            $field['express_longtitude'] = $returnInfo['delivererLng'];
            $field['express_latitude'] = $returnInfo['delivererLat'];
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5003;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');

            if ($r_e_d && $r_o && $r_e) {
                $return = 'success';
                $log->lwrite('finish response=>' . $returnInfo['orderNo'] . ',' . $return);
                echo $return;
                exit;
            }

        }
    }




    /**
     * 上正式机 需要调此接口  2019-11-20 讨论不用再次执行此方法 直接copy表到正式机
     * 达达 查看城市代码 暂无更新数据功能
     */
    public function  GetCityCodeAction(){
        $dde = new DDExpressClass(TRUE);
        $info = $dde->getCityCode();
        foreach($info['result'] as $val){
            $addItem['city_name'] = $val['cityName'];
            $addItem['city_code'] = $val['cityCode'];
            $addItem['createdt'] = 'now()';
            $this->model->addItem($addItem,'city_code');
        }
        echo 'OK';
    }




    /**
     * 上正式机 需要调此接口  2019-11-20 讨论不用再次执行此方法 直接copy表到正式机
     * @return mixed 获取取消代码 暂无更新数据功能
     */
    public function GetDDCancelCodeAction()
    {
        $dde = new DDExpressClass(TRUE);
        $result = $dde->reasonsReasons();
        foreach($result['result'] as $val){
            $addItem['cancel_name'] = $val['reason'];
            $addItem['cancel_code'] = $val['id'];
            $addItem['createdt'] = 'now()';
            $this->model->addItem($addItem,'cancel_code');
        }
        echo 'OK';
    }





    /**
     * 仅手动测试用
     * 达达 模拟回调取消
     * status = 	响应状态，成功为"success"，失败为"fail"
     * code = 响应返回码
     * msg = 响应描述
     * result = 响应结果
     */
    public function DDcancelAction()
    {
        $dde = new DDExpressClass(TRUE,73753,'dada49da12778ddac4b','2d5a37a0ba36548b084aa5820551073e');
        $data = ['order_id'=>'100046_PH16081200005492_100'];
        $result = $dde->DDcancel($data);
        echo '<pre>';
        var_dump($result);
    }

    /**
     * 仅手动测试用
     * 达达 模拟回调接单
     * status = 	响应状态，成功为"success"，失败为"fail"
     * code = 响应返回码
     * msg = 响应描述
     * result = 响应结果
     */
    public function DDacceptAction()
    {
        $dde = new DDExpressClass(TRUE,73753,'dada49da12778ddac4b','2d5a37a0ba36548b084aa5820551073e');
        $data = ['order_id'=>'100046_MT27009294047235596_386'];
        $result = $dde->DDaccept($data);
        echo '<pre>';
        var_dump($result);
    }


    /**
     * 仅手动测试用
     * 达达 模拟回调取货
     * status = 	响应状态，成功为"success"，失败为"fail"
     * code = 响应返回码
     * msg = 响应描述
     * result = 响应结果
     */
    public function DDfetchAction()
    {
//        $dde = new DDExpressClass(TRUE,19529,'dada49da12778ddac4b','2d5a37a0ba36548b084aa5820551073e');
        $dde = new DDExpressClass(TRUE,73753,'dada49da12778ddac4b','2d5a37a0ba36548b084aa5820551073e');

        $data = ['order_id'=>'100046_MT27009294047235596_386'];
        $result = $dde->DDfetch($data);
        echo '<pre>';
        var_dump($result);
    }

    /**
     * 仅手动测试用
     * 达达 模拟回调完成
     * status = 	响应状态，成功为"success"，失败为"fail"
     * code = 响应返回码
     * msg = 响应描述
     * result = 响应结果
     */
    public function DDfinishAction()
    {
        $dde = new DDExpressClass(TRUE,73753,'dada49da12778ddac4b','2d5a37a0ba36548b084aa5820551073e');
        $data = ['order_id'=>'100046_MT27009294047235596_386'];
        $result = $dde->DDfinish($data);
        echo '<pre>';
        var_dump($result);
    }



    /**
     * 查看门店信息
     */
    public function detailAction()
    {
        $dde = new DDExpressClass(TRUE,19529,'dada49da12778ddac4b','2d5a37a0ba36548b084aa5820551073e');
        $originShopId = '100047';  # 门店编号
        $parameter = [
            'origin_shop_id' => $originShopId,
        ];
        $result = $dde->detail($parameter);
        echo '<pre>';
        var_dump($result);
    }
    /**
     * 查询运费账户类型（1：运费账户；2：红包账户，3：所有），默认查询运费账户余额
     * 返回   redPacketBalance = 红包    deliverBalance = 余额
     */
    public function balanceQueryAction()
    {
        $dde = new DDExpressClass(TRUE,19529,'dada49da12778ddac4b','2d5a37a0ba36548b084aa5820551073e');
        $parameter = [
            'category' => 3,
        ];
        $result = $dde->balanceQuery($parameter);
        echo '<pre>';
        var_dump($result);
    }




    /**
     * 订单状态(待接单＝1,待取货＝2,配送中＝3,已完成＝4,已取消＝5, 已过期＝7,指派单=8,妥投异常之物品返回中=9, 妥投异常之物品返回完成=10,骑士到店=100,创建达达运单失败=1000 可参考文末的状态说明）
     * {"order_status":4,"cancel_reason":"","update_time":1560476810,"cancel_from":0,"dm_id":666,"signature":"dc83f298e80522bd8d6fca983debfb8d","dm_name":"达达骑手","order_id":"100046_PH19061100000961_133","client_id":"277089847102854","dm_mobile":"13546670420"}
     * 无返回配送人坐标
     */
    public function GetDDCallBackAction(){
        $body = file_get_contents('php://input');
        $log = new Logging();
        $log->lfile('dd_callback');
        $log->lwrite('finish body=>' . $body);
        $returnInfo = json_decode($body, true);
        $log->lwrite('finish receive=>' . json_encode($returnInfo, JSON_UNESCAPED_UNICODE));
        $config = Config::getInstance();
        $website_array = $config->getWebSiteConfig();
        if (!empty($returnInfo) && $returnInfo['order_status'] == 1 || $returnInfo['order_status'] == 2 || $returnInfo['order_status'] == 3 || $returnInfo['order_status'] == 4 || $returnInfo['order_status'] == 5 || $returnInfo['order_status'] == 7 || $returnInfo['order_status'] == 8 || $returnInfo['order_status'] == 9 || $returnInfo['order_status'] == 10 || $returnInfo['order_status'] == 1000) {
            if($returnInfo['order_status'] == 1){
                $shop_status = 2;
                $express_code_desc = '待接单';
                # 推送小费
//                , 'shop_no'=>$store_no[0]['shop_no']
                $where = array('AND'=>array('='=>array('order_no' => $returnInfo['order_id'],"isdeleted" => 0, "status" => 1)));
                $tip_res = $this->model->getItemByOther($where,'tip_list');
                        $log->lwrite('查找小费信息=>' . json_encode($tip_res,JSON_UNESCAPED_UNICODE));
                if($tip_res && count((array)$tip_res) > 0){

                    # 查找门店编号
                    $where_store = array('AND'=>array('='=>array('shop_express_no' => $returnInfo['order_id'], "isdeleted" => 0, "status" => 2)));
                    $store_no = $this->model->getItemByOther($where_store,'orders_express');
                    $log->lwrite('查找门店编号=>' . json_encode($store_no,JSON_UNESCAPED_UNICODE));
                    if($store_no && count($store_no) > 0){
                        # 查找门店快点参数
                        $where_store = array('AND'=>array('='=>array('store_id' => $store_no[0]['shop_no'], "isdeleted" => 0, "zp_status" => 1)));
                        $store_res = $this->model->getItemByOther($where_store,'xd_store');
                        $log->lwrite('查找门店快点参数=>' . json_encode($store_res,JSON_UNESCAPED_UNICODE));

                        if($store_res && count($store_res) > 0){
                            $city     = explode('市', $store_res[0]['front_city']);
                            $log->lwrite('门店所在城市名称=>' . $city[0]);

                            $cityCode = '';
                            # 获取城市代码
                            $where_fields_city = array("AND" => array("=" => array('status' => 1, 'isdeleted' => 0)));
                            $field_city = 'city_code,city_name';
                            $cityCodeList = $this->model->getAll($where_fields_city, 'city_code', '', $field_city);
                            if($cityCodeList && count($cityCodeList) > 0){
                                foreach ($cityCodeList as $ctval) {
                                    if ($city[0] == $ctval['city_name']) {
                                        $cityCode = $ctval['city_code'];
                                    }
                                }
                            }
                            $log->lwrite('城市代码=>' . json_encode($cityCodeList,JSON_UNESCAPED_UNICODE));
                            $tips = 0;
                            $tip_remark = '';
                            $tipIDs = [];
                            foreach($tip_res as $k=>$t){
                                $tips += $t['price'];
                                $tipIDs[$k]['id'] = $t['id'];
                                $tip_remark .= isset($t['tip_remark']) ? '备注'.($k+1).':'.$t['tip_remark'] :''.' ';
                            }
                            $log->lwrite('推送小费信息=> 订单编号：' .$returnInfo['order_id'].' ++++++ 小费总额：' .$tips .' ++++++ 城市代码：' . $cityCode . ' ++++++ 小费备注：'.$tip_remark);
                            $dde = new DDExpressClass($website_array['debug'],$store_res[0]['dd_source_id'],$store_res[0]['dd_app_key'],$store_res[0]['dd_app_secret']);
                            $addFee = $dde->addTip($returnInfo['order_id'],$tips,$cityCode,$tip_remark);
                            $log->lwrite('小费返回信息=>' . json_encode($addFee,JSON_UNESCAPED_UNICODE));
                            if($addFee && $addFee['error_code'] == 0){
                                $tip['push_state'] = 1;
                            }else{
                                $tip['push_state'] = 9;
                            }
                            $tip['push_time'] = 'now()';
                            $tip['ret_data'] = json_encode($addFee,JSON_UNESCAPED_UNICODE);
                            foreach ($tipIDs as $v) {
                                $where_fields = array("AND" => array("=" => array('id' => $v['id'], "isdeleted" => 0)));
                                $this->model->updateItem($tip, $where_fields, 'tip_list');
                            }
                        }
                    }
                }

            }elseif ($returnInfo['order_status'] == 2) {
                $shop_status = 3;
                $express_code_desc = '待取件';
            } elseif ($returnInfo['order_status'] == 3) {
                $shop_status = 4;
                $express_code_desc = '配送中';
            } elseif ($returnInfo['order_status'] == 4) {
                $shop_status = 5;
                $express_code_desc = '配送完成';
            } elseif($returnInfo['order_status'] == 5) {
                $shop_status = 8;
                $express_code_desc = '异常-已经消订单';
            } elseif($returnInfo['order_status'] == 7) {
                $shop_status = 8;
                $express_code_desc = '异常-已过期';
            } elseif($returnInfo['order_status'] == 8) {
                $shop_status = 2;
                $express_code_desc = '待接单';
            }elseif($returnInfo['order_status'] == 9){
                $shop_status = 8;
                $express_code_desc = '异常-妥投异常之物品返回中';
            }elseif($returnInfo['order_status'] == 10){
                $shop_status = 8;
                $express_code_desc = '异常-妥投异常之物品返回完成';
            }elseif($returnInfo['order_status'] == 100){
                $shop_status = 3;
                $express_code_desc = '待取件';
            }else{
                $shop_status = 8;
                $express_code_desc = '异常-创建达达运单失败';
            }

            $_result = array();
            $_result['shop_express_no'] = $returnInfo['order_id'];
            $_result['express_no'] = $returnInfo['client_id'];
            $_result['express_type'] = 'dd';
            $_result['express_code'] = '';
            $_result['express_code_desc'] = $express_code_desc;
            $_result['express_data'] = json_encode($returnInfo, JSON_UNESCAPED_UNICODE);
            $_result['express_result'] = "OK";
            $_result['shop_code'] = $shop_status;
            $_result['shop_code_desc'] = Data::$_express_status[$shop_status];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5002;
            $log->lwrite('status add express_data=>' . json_encode($_result, JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');

            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields, 'orders_express');

            $field = array();
            if($shop_status == 8){
                $field['status'] = 0;
                $field['express_type'] = '';
            }else{
                $field['status'] = $shop_status;
            }
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5002;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');


            $field = array();
            $field['status'] = $shop_status;
            $field['express_courier'] = $returnInfo['dm_name'];
            $field['express_mobile'] = $returnInfo['dm_mobile'];
            $field['express_longtitude'] = '';
            $field['express_latitude'] = '';
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5002;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');
//            || $shop_status == 5
            if($shop_status == 4 ){
                $data['shop_no'] = $order_express[0]['shop_no'];
                $data['orders_id'] = $order_express[0]['orders_id'];
                $data['notice_consignee'] = $order_express[0]['notice_consignee'];
                $data['rider_name'] = $returnInfo['dm_name'];;
                $data['rider_tel'] =  $returnInfo['dm_mobile'];
                $this->OrgData($data);
            }
            if ($r_e_d && $r_o && $r_e) {
                $return = 200;
                $log->lwrite('finish response=>' . $returnInfo['orderNo'] . ',' . $return);
                echo $return;
                exit;
            }

        }
        echo 200;
    }





    /**
     * 订单状态订单状态，-1：订单已取消；0：订单未付款；1：订单待接单；2：订单配送中 ；3：订单已完成 ；4：订单待取货
     * 返回方式 GET
     */
    public function JRDCallBackAction(){
        $returnInfo = $_GET;
        $log = new Logging();
        $log->lfile('jrd_callback');
        $log->lwrite('finish receive=>' . json_encode($returnInfo, JSON_UNESCAPED_UNICODE));
        if (!empty($returnInfo)) {
            if($returnInfo['status'] == 0 || $returnInfo['status'] == 1 ){
                $shop_status = 2;
                $express_code_desc = '待接单';
            }elseif ($returnInfo['status'] == 4) {
                $shop_status = 3;
                $express_code_desc = '待取件';
            }elseif($returnInfo['status'] == 2){
                $shop_status = 4;
                $express_code_desc = '配送中';
            }elseif($returnInfo['status'] == 3){
                $shop_status = 5;
                $express_code_desc = '已完成';
            }else{
                $shop_status = 8;
                $express_code_desc = '已经消订单';
            }

            $_result = array();
            $_result['shop_express_no'] = $returnInfo['partner_order_no'];
            $_result['express_no'] = $returnInfo['order_no'];
            $_result['express_type'] = 'jrd';
            $_result['express_code'] = '';
            $_result['express_code_desc'] = $express_code_desc;
            $_result['express_data'] = json_encode($returnInfo, JSON_UNESCAPED_UNICODE);
            $_result['express_result'] = "OK";
            $_result['shop_code'] = $shop_status;
            $_result['shop_code_desc'] = Data::$_express_status[$shop_status];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5002;
            $log->lwrite('status add express_data=>' . json_encode($_result, JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');

            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields, 'orders_express');

            $field = array();
            if($shop_status == 8){
                $field['status'] = 0;
                $field['express_type'] = '';
            }else{
                $field['status'] = $shop_status;
            }
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5002;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');


            $field = array();
            $field['status'] = $shop_status;
            $field['express_courier'] = $returnInfo['delivery_staff_name'];
            $field['express_mobile'] = $returnInfo['delivery_staff_contract'];
            $field['express_longtitude'] = '';
            $field['express_latitude'] = '';
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5002;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');

            if($shop_status == 4){
                $data['shop_no'] = $order_express[0]['shop_no'];
                $data['orders_id'] = $order_express[0]['orders_id'];
                $data['notice_consignee'] = $order_express[0]['notice_consignee'];
                $data['rider_name'] = $returnInfo['delivery_staff_name'];
                $data['rider_tel'] = $returnInfo['delivery_staff_contract'];
                $this->OrgData($data);
            }
            if ($r_e_d && $r_o && $r_e) {
                $return = 200;
                $log->lwrite('finish response=>' . $returnInfo['partner_order_no'] . ',' . $return);
                echo $return;
                exit;
            }
        }
        echo 'SUCCESS';
    }




    /**
     * 订单状态订单状态，-1：订单已取消；0：订单未付款；1：订单待接单；2：订单配送中 ；3：订单已完成 ；4：订单待取货
     * 返回方式 GET
     */
    public function JRDFinishAction(){
        $returnInfo = $_GET;
        $log = new Logging();
        $log->lfile('jrd_finish');
        $log->lwrite('finish receive=>' . json_encode($returnInfo, JSON_UNESCAPED_UNICODE));
        if (!empty($returnInfo)){
            $_result=array();
            $_result['shop_express_no'] = $returnInfo['partner_order_no'];
            $_result['express_no'] = $returnInfo['order_no'];
            $_result['express_type'] = 'jrd';
            $_result['express_code'] = $returnInfo['status'];
            $_result['express_data'] = json_encode($returnInfo,JSON_UNESCAPED_UNICODE);
            $_result['express_code_desc'] = '';
            $_result['express_result']="OK";
            $_result['shop_code'] = 5;
            $_result['shop_code_desc'] = Data::$_express_status[5];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5001;
            $log->lwrite('finish add express_data=>'.json_encode($_result,JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');


            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields,'orders_express');

            //更新订单状态
            $field = array();
            $field['status'] = 5;
            $field['updatedt'] = 'now()';
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');

            //更新指派订单状态
            $where_fields_exp = array("AND" => array("=" => array('id' => $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields_exp, 'orders_express');
//            $data['shop_no'] = $order_express[0]['shop_no'];
//            $data['orders_id'] = $order_express[0]['orders_id'];
//            $data['notice_consignee'] = $order_express[0]['notice_consignee'];
//            $data['rider_name'] = $returnInfo['delivery_staff_name'];
//            $data['rider_tel'] = $returnInfo['delivery_staff_contract'];
//            $this->OrgData($data);
            if($r_e_d && $r_o && $r_e){
                $return = ["error_code"=>0,"error_msg"=>"success"];
                $log->lwrite('finish response=>'.$returnInfo['partner_order_no'].','.json_encode($return,JSON_UNESCAPED_UNICODE));
                echo  json_encode($return, JSON_UNESCAPED_UNICODE);
                exit;
            }
        }
        echo 'SUCCESS';
    }


    /**
     * UU回调
     * 当前状态1下单成功 3跑男抢单 4已到达 5已取件 6到达目的地 10收件人已收货 -1订单取消
     */
    public function UUCallBackAction(){
        $returnInfo = $_POST;
        $log = new Logging();
        $log->lfile('uu_callback');
        $log->lwrite('finish receive=>' . json_encode($returnInfo['data'], JSON_UNESCAPED_UNICODE));

        $returnInfo = json_decode($returnInfo['data'],true);
        if (!empty($returnInfo) && $returnInfo['return_code'] == 'ok') {
            if( $returnInfo['state'] == 1 ){
                $shop_status = 2;
                $express_code_desc = '待接单';
            }elseif ($returnInfo['state'] == 3) {
                $shop_status = 3;
                $express_code_desc = '待取件';
            }elseif($returnInfo['state'] == 4 || $returnInfo['state'] == 5 || $returnInfo['state'] == 6){
                $shop_status = 4;
                $express_code_desc = '配送中';
            }elseif($returnInfo['state'] == 10){
                $shop_status = 5;
                $express_code_desc = '已完成';
            }else{
                $shop_status = 8;
                $express_code_desc = '已经消订单';
            }

            $_result = [];
            $_result['shop_express_no'] = $returnInfo['origin_id'];
            $_result['express_no'] = $returnInfo['order_code'];
            $_result['express_type'] = 'uu';
            $_result['express_code'] = '';
            $_result['express_code_desc'] = $express_code_desc;
            $_result['express_data'] = json_encode($returnInfo, JSON_UNESCAPED_UNICODE);
            $_result['express_result'] = "OK";
            $_result['shop_code'] = $shop_status;
            $_result['shop_code_desc'] = Data::$_express_status[$shop_status];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5002;
            $log->lwrite('status add express_data=>' . json_encode($_result, JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');

            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields, 'orders_express');

            $field = [];
            if($shop_status == 8){
                $field['status'] = 0;
                $field['express_type'] = '';
            }else{
                $field['status'] = $shop_status;
            }
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5002;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');


            $field = [];
            $field['status'] = $shop_status;
            $field['express_courier'] = $returnInfo['driver_name'];
            $field['express_mobile'] = $returnInfo['driver_mobile'];
            $field['express_longtitude'] = '';
            $field['express_latitude'] = '';
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5002;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');

//            || $shop_status == 5
            if($shop_status == 4){
                $data['shop_no'] = $order_express[0]['shop_no'];
                $data['orders_id'] = $order_express[0]['orders_id'];
                $data['notice_consignee'] = $order_express[0]['notice_consignee'];
                $data['rider_name'] = $returnInfo['delivery_staff_name'];
                $data['rider_tel'] = $returnInfo['delivery_staff_contract'];
                $this->OrgData($data);
            }
            if ($r_e_d && $r_o && $r_e) {
                $return = 200;
                $log->lwrite('finish response=>' . $returnInfo['origin_id'] . ',' . $return);
                echo $return;
                exit;
            }
        }
    }

    /**
     * 365回调
     * 配送状态：1待处理,2已接单/待取餐,3配送中，4已送达,5已取消
*/
    public function SLWCallBackAction(){
        $body = file_get_contents('php://input');
        $log = new Logging();
        $log->lfile('slw_callback');
        $returnInfo = json_decode($body, true);
        $log = new Logging();
        $log->lwrite('finish receive=>' . json_encode($returnInfo, JSON_UNESCAPED_UNICODE));

        if (!empty($returnInfo) && $returnInfo['orderId']) {
            if( $returnInfo['deliveryStatus'] == 1 ){
                $shop_status = 2;
                $express_code_desc = '待接单';
            }elseif ($returnInfo['deliveryStatus'] == 2) {
                $shop_status = 3;
                $express_code_desc = '待取件';
            }elseif($returnInfo['deliveryStatus'] == 3){
                $shop_status = 4;
                $express_code_desc = '配送中';
            }elseif($returnInfo['deliveryStatus'] == 4){
                $shop_status = 5;
                $express_code_desc = '已完成';
            }else{
                $shop_status = 8;
                $express_code_desc = '已经消订单';
            }

            $_result = [];
            $_result['shop_express_no'] = $returnInfo['tpOrderId'];
            $_result['express_no'] = $returnInfo['orderId'];
            $_result['express_type'] = 'slw';
            $_result['express_code'] = '';
            $_result['express_code_desc'] = $express_code_desc;
            $_result['express_data'] = json_encode($returnInfo, JSON_UNESCAPED_UNICODE);
            $_result['express_result'] = "OK";
            $_result['shop_code'] = $shop_status;
            $_result['shop_code_desc'] = Data::$_express_status[$shop_status];
            $_result['createdt'] = 'now()';
            $_result['create_id'] = 5002;
            $log->lwrite('status add express_data=>' . json_encode($_result, JSON_UNESCAPED_UNICODE));
            $r_e_d = $this->model->addItem($_result, 'express_data');

            $where_fields = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'])));
            $order_express = $this->model->getItemByOther($where_fields, 'orders_express');

            $field = [];
            if($shop_status == 8){
                $field['status'] = 0;
                $field['express_type'] = '';
            }else{
                $field['status'] = $shop_status;
            }
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5002;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');


            $field = [];
            $field['status'] = $shop_status;
            $field['express_courier'] = $returnInfo['deliverer'];
            $field['express_mobile'] = $returnInfo['delivererPhone'];
            $field['express_longtitude'] = '';
            $field['express_latitude'] = '';
            $field['updatedt'] = 'now()';
            $field['update_id'] = 5002;
            $where_fields = array("AND" => array("=" => array('id' => $order_express[0]['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');

//            || $shop_status == 5
            if($shop_status == 4){
                $data['shop_no'] = $order_express[0]['shop_no'];
                $data['orders_id'] = $order_express[0]['orders_id'];
                $data['notice_consignee'] = $order_express[0]['notice_consignee'];
                $data['rider_name'] = $returnInfo['deliverer'];
                $data['rider_tel'] = $returnInfo['delivererPhone'];
                $this->OrgData($data);
            }
            if ($r_e_d && $r_o && $r_e) {
                $return = 0;
                $log->lwrite('finish response=>' . $returnInfo['origin_id'] . ',' . $return);
                echo $return;
                exit;
            }
        }
    }



    private function OrgData($data){
        # 推送配货通知
        $where_fields = array("AND" => array("=" => array('store_id' => $data['shop_no'])));
        $store = $this->model->getItemByOther($where_fields, 'xd_store');
        $order = $this->model->getItemById($data['orders_id'],'orders');
        $short = $this->EncodeShort($data);

        $log = new Logging();
        $log->lfile('OrgData');
        $log->lwrite('data ...=>:' .json_encode($data,true).'order...=>'.json_encode($order,true));

        $this->NoticeConsignee([
            'store_tel' => $store[0]['tel'],
            'rider_tel' => $data['rider_tel'],
            'rider_name' => $data['rider_name'],
            'short_link' => $short ,
            'oid' => $data['orders_id'],
            'receiver_tel' => $order['receiver_tel'],
            'buyer_mobile' => !empty($order['buyer_mobile']) ? $order['buyer_mobile'] :'' ,
            'notice_consignee' => $data['notice_consignee']
        ]);
    }

    /**
     * 通知收货人
     * @param array $parameter
     */
    private function NoticeConsignee(array $parameter)
    {
        # A. 订购人手机号与收货人手机号相同时，只通知订购者手机号
        # B. 订购人手机号与收货人手机号不同时，两个手机号都推送通知
        # C. 如门店勾选了不通知收货人时，那就只通知订购人，如没有订购人手机号，那就不通知
        if($parameter['notice_consignee'] == 2){    # 推俩
            $phone = $parameter['receiver_tel'];
            $data['content'] = '位置：'.$parameter['short_link'];
            $code = 123;
            $cloundsms=new CloudSMS();
            $cloundsms->sendMessages($phone,$code);
        }
        if($parameter['buyer_mobile']){
            $phone = $parameter['buyer_mobile'];
            $data['content'] = '位置：'.$parameter['short_link'];
            $code = 123456;
            $cloundsms=new CloudSMS();
            $cloundsms->sendMessages($phone,$code);

        }
//        $Config = Config::getInstance();
//        $webSite = $Config->getWebSiteConfig();
//        $tid = 'S000008';
//        $d['c'] = 'zhaipei';
//        $d['tid'] = $tid;
//        $sendC = new SendSMSClass();
//        $TemplateData = $sendC->getTemplateData($webSite['debug'], $d);
//        $TemplateData = json_decode($TemplateData, true);
//        if ($TemplateData['errorcode'] == 0) {
//            $riderNames = $this->params['ridername'];
//            $field['status'] = 3;
//            $riderName = explode('_', $riderNames);
//            $field['express_courier'] = $riderName[1];
//            $field['express_mobile'] = $riderName[2];
//            $field['express_fee'] = $this->params['shop_rider_fee'];
//            $field['QRCode'] = rand(0, 999999);
//            $status = 3;
//            $where_field_edit = array("AND" => array("=" => array('createid' => $_SESSION['zp_shop']['store_id'], 'isdeleted' => 0, 'status' => 1, 'orders_id' => $order['id'])));
//            $shop_delivery_address = $this->model->getItemByOther($where_field_edit, 'shop_delivery_address');
//            if ($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0) {
//                $receiver_address = $shop_delivery_address[0]['receiver_address'];
//            } else {
//                $receiver_address = $order['receiver_address'];
//            }
//
//            $first = '有一笔订单指派给您，请尽快前往骑手端查看！';
//            $remark = '请尽快前往门店取货配送！';
//            $SendData['c'] = 'zhaipei';
//            $SendData['tid'] = $tid;
//            $SendData['phoneNumber'] = $riderName[2];
//            $SendData['contentVar']['sms']['first'] = $first;
//            $SendData['contentVar']['sms']['keyword1'] = $order['shop_name'];
//            $SendData['contentVar']['sms']['keyword2'] = $shops[0]['front_area'] . $shops[0]['front_address'];
//            $SendData['contentVar']['sms']['keyword3'] = $receiver_address;
//            $SendData['contentVar']['sms']['keyword4'] = date('Y-m-d H:i:s');
//            $SendData['contentVar']['sms']['remark'] = $remark;
//
//            $SendData['contentVar']['wx']['first'] = $first;
//            $SendData['contentVar']['wx']['keyword1'] = $order['shop_name'];
//            $SendData['contentVar']['wx']['keyword2'] = $shops[0]['front_area'] . $shops[0]['front_address'];
//            $SendData['contentVar']['wx']['keyword3'] = $receiver_address;
//            $SendData['contentVar']['wx']['keyword4'] = date('Y-m-d H:i:s');
//            $SendData['contentVar']['wx']['remark'] = $remark;
//            $s = $sendC->sendSMS($webSite['debug'], $SendData);
//        }
    }


    private function EncodeShort($data)
    {
        $where = array("AND" => array("=" => array('oid'=>$data['orders_id'])));
        $link = $this->model->getItemByOther($where,'short_link');

        $config = Config::getInstance();
        $website_array = $config->getWebSiteConfig();
        $host = $website_array['website_url'] ;
        if($link && $link[0]['short_link']){
            return $host.$link[0]['short_link'];
        }else{
            $key_str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            $key = 'DW'.substr(str_shuffle($key_str),mt_rand(0,strlen($key_str)-11),4);
            $fields['short_link'] = $key;
            $fields['oid'] = $data['orders_id'];
            $fields['createdt'] = 'now()';
            $this->model->addItem($fields,'short_link');
            return $host.$key;
        }
    }

    /**
     * 手机验证
     */
    public function CheckPhoneAction(){
        $REDIRECT_URL =  substr($_SERVER['REDIRECT_URL'],1);
        $this->view->setVariable("short_link", $REDIRECT_URL);
        $this->view->setVariable("title", '手机验证');
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    /**
     * 手机验证
     */
    public function CheckPhone2Action(){
        $phone = (!empty($this->params['phone'])) ? $this->params['phone'] : '';                            # 手机号
        $checkCode = (!empty($this->params['checkcode'])) ? $this->params['checkcode'] : '';                # 验证码
        $short_link = (!empty($this->params['short_link'])) ? $this->params['short_link'] : '';

        $where = array("AND" => array("=" => array('short_link'=>$short_link)));
        $link = $this->model->getItemByOther($where,'short_link');
        if(!$link[0]['oid']){
            echo json_encode(['status'=>0,'msg'=>'该链接不存在']);
            exit;
        }
        $order = $this->model->getItemById($link[0]['oid'],'orders');
        if($order['receiver_tel'] != $phone && $order['buyer_mobile'] != $phone){
            echo json_encode(['status'=>0,'msg'=>'该手机号码没有权限查看当前订单配送位置']);
            exit;
        }


        # 判断验证码是否有效
        $sql = "select * from check_phone where temp_phone = '$phone' AND status = 1 order by createdt desc ";
        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $checkPhone[] = $row;
            }
        }
        if(!$checkPhone){
            echo json_encode(['status'=>0,'msg'=>'无效手机号']);
            exit;
        }
        $begin = strtotime($checkPhone[0]['createdt']);
        $end = time();
        $difference = $this->timediff($begin,$end);
        if($difference['min'] >= 5){
            $columns['temp_phone'] = $phone;
            $columns['status'] = 0;
            $whereU = array("AND" => array("=" => array('temp_phone'=>$phone, "status"=>1)));
            $this->model->updateItem($columns,$whereU,'check_phone');
            echo json_encode(['status'=>0,'msg'=>'验证码失效']);
            exit;
        }

        if($checkPhone[0]['code'] == $checkCode){
            $columns['temp_phone'] = $phone;
            $columns['status'] = 0;
            $whereU = array("AND" => array("=" => array('temp_phone'=>$phone, "status"=>1)));
            $this->model->updateItem($columns,$whereU,'check_phone');
            echo json_encode(['status'=>'success','msg'=>'']);
        }else{
            echo json_encode(['status'=>'error','msg'=>'验证码错误']);
        }
    }

    function timediff($begin_time,$end_time)
    {
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        $timediff = $endtime-$starttime;
        $remain = $timediff%86400;
        $remain = $remain%3600;
        $mins = intval($remain/60);
        $secs = $remain%60;
        $res = array("min" => $mins,"sec" => $secs);
        return $res;
    }

    /**
     * 解码 骑手位置
     */
    public function LocationAction(){
        $short_link = (!empty($this->params['short_link'])) ? $this->params['short_link'] : '';
        $where = array("AND" => array("=" => array('short_link'=>$short_link)));
        $link = $this->model->getItemByOther($where,'short_link');
        $order = $this->model->getItemById($link[0]['oid'],'orders');
        $where = array("AND" => array("=" => array('orders_id'=>$order['id'],'ph_no'=>$order['ph_no'],'status'=>$order['status'])));
        $orders_express = $this->model->getItemByOther($where,'orders_express');
        if($order['status'] == 5){
            $express_code_desc = '已完成';
        }else{
            $express_code_desc = '配送中';
        }
        $this->view->setVariable("express_type", $orders_express[0]['express_type']);
        $this->view->setVariable("shop_express_no", $orders_express[0]['shop_express_no']);
        $this->view->setVariable("shop_no", $orders_express[0]['shop_no']);
        $this->view->setVariable("lng", $order['lng']);
        $this->view->setVariable("lat", $order['lat']);
        $this->view->setVariable("express_order_no", $orders_express[0]['express_order_no']);
        $this->view->setVariable("rider_name", $orders_express[0]['express_courier']);
        $this->view->setVariable("rider_tel", $orders_express[0]['express_mobile']);
        $this->view->setVariable("express_code_desc", $express_code_desc);
        $this->view->setVariable("otime", $order['updatedt']);
        $this->view->setVariable("status", $order['status']);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

}